<?php

require_once 'classes/LightPressPlugin.php';

class PostMeta extends LightPressPlugin {

    var $default_context = LP_CONTEXT_ALL;
    var $active = true;
    var $hooks = array('get_posts_loop');

    var $description = 'Adds template tags for post meta values';
    var $constructor_args = array('hide_missing' => 'Hide tags for missing meta keys (recommended)',
                                  'unique_key' => 'Assume each meta key is unique');
    var $hide_missing = 1;
    var $unique_key = 1;
    
    var $_frontend;
	var $_db;
	
	var $_metatable;
	var $_metadata = null;
    var $_metakeys = array();
	var $_metacached = false;	// indicates meta data already cached
	

    function PostMeta(&$frontend, $args, $dummy_run=false) {
        $this->LightPressPlugin($frontend, $args, $dummy_run);
		$this->_db =& $frontend->db;
		$this->_metatable =& $frontend->tables['postmeta'];
	}

	function getMetaData($id=0) {
		
		if (!$this->_metacached && isset($this->_frontend->posts_in)) {
			// force post cache load if not already done
			//$posts =& $this->_frontend->getPosts();
			
            // retrieve post meta data
			$qry = "SELECT DISTINCT post_id, meta_id, meta_key, meta_value
					FROM {$this->_metatable} " .
					(($id >= 0) ? " WHERE post_id in ({$this->_frontend->posts_in}) " : '') .
				   "ORDER BY post_id, meta_id";
			$this->_db->query($qry);
			
			$posts_meta = array(array(array()));
			foreach ($this->_db->all() as $meta)
				$posts_meta[ $meta['post_id'] ][ $meta['meta_key'] ][] = $meta['meta_value'];
			
			$this->_metadata =& $posts_meta;
			
			// could assign to main posts array?
			/*foreach ($posts as $index => $post) {
				if (isset($posts_meta[ $post['post_id'] ]))
					$posts[$index]['post_meta'] =& $posts_meta[ $post['post_id'] ];
				else
					$posts[$index]['post_meta'] = array();
			}*/
            
            if ($this->hide_missing) {
                // retrieve post keys
                $qry = "SELECT meta_key " .
                        (($this->unique_key) ? '' : " COUNT(post_id) AS key_count ") .
                       "FROM {$this->_metatable} " .
                        (($this->unique_key) ? '' : " GROUP BY post_id, meta_key ") .
                       "ORDER BY meta_key ";
                $this->_db->query($qry);
                
                $keys =& $this->_metakeys;
                foreach ($this->_db->all() as $meta) {
                    if ($this->unique_key) {
                        $keys[] = strtolower($meta['meta_key']);
                    } else {
                        for ($i=1; $i <= $meta['key_count']; $i++)
                            $keys[] = strtolower($meta['meta_key']) . $i;
                    }
                }
            }
            
			$this->_metacached = true;
		}
		
		if ($id > 0) {
			if (isset($this->_metadata[$id]))
				return ($this->_metadata[$id]);
			else
				return (array());
		}
		else
			return ($this->_metadata);
	}
    
    function getMetaKeys() {
        // build meta cached if necessary
        if (!$this->_metacached)
            $this->getMetaData();
            
        return $this->_metakeys;
    }
    
    function run($hook, &$post) {
    
        /* assign meta values to template tags {post_meta_<metakey><#>} where <#> is the count of the meta value (starting at 1)
          (blank if $unique_key is true) */
        $postmeta =& $this->getMetaData($post['post_id']);
        $tpl =& $this->_frontend->tpl;

        foreach($postmeta as $key=>$meta) {
            foreach($meta as $count=>$value) {
                $post['post_meta_' . strtolower($key) . (($this->unique_key) ? '' : ($count+1) ) ] = $value;
            }
        }
        
        /* assign blank value to all meta values that don't exist for this post */
        if ($this->hide_missing) {
            foreach($this->_metakeys as $key) {
                if (!isset($post['post_meta_' . $key]))
                    $post['post_meta_' . $key] = '';
            }
        }
    }
    
    function hide() {
        // do nothing?
    }
}

?>